package net.entelijan.cobean.bind.impl;

import java.util.List;

import net.entelijan.cobean.bind.IBinding;
import net.entelijan.cobean.bind.IItemWrapper;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

class SpringPropertyItemWrapper implements IItemWrapper {

    private List<? extends IBinding<?>> entryBindings;

    private BeanWrapper wItem;

    public SpringPropertyItemWrapper() {
        super();
    }

    public SpringPropertyItemWrapper(List<? extends IBinding<?>> entryBindings, Object inner) {
        this();
        this.entryBindings = entryBindings;
        this.wItem = new BeanWrapperImpl(inner);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (this.entryBindings != null && this.entryBindings.size() > 0) {
            int count = 0;
            for (IBinding<?> eb : this.entryBindings) {
                if (count > 0) {
                    sb.append(" ");
                }
                sb.append(this.wItem.getPropertyValue(getModelProperty(eb)));
                count++;
            }
        } else {
            String str;
            if (this.wItem.getWrappedInstance() instanceof Enum<?>) {
                Enum<?> eval = (Enum<?>) this.wItem.getWrappedInstance();
                str = eval.toString();
            } else {
                str = this.wItem.getWrappedInstance().toString();
            }
            sb.append(str);
        }
        return sb.toString();
    }

    private <T> String getModelProperty(IBinding<T> eb) {
        if (eb instanceof NestedBinding<?>) {
            IBinding<T> innerBinding = ((NestedBinding<T>) eb).getInnerBinding();
            return eb.getModelProperty() + "." + getModelProperty(innerBinding);
        }
        return eb.getModelProperty();
    }

    public Object getWrappedObject() {
        return this.wItem.getWrappedInstance();
    }

}
